//
//  CQueueList.c
//  CircleQueue
//
//  Created by Xavier on 2023/10/23.
//

#include "CQueueList.h"

//初始化循环队列
CQueue* circularQueueInit(int len) {
    CQueue* cq = (CQueue*)malloc(sizeof(CQueue*));
    int* tmp = (int*)malloc(sizeof(int)*len+1);//多开一个空间
    if (tmp == NULL) {
        printf("malloc error!\n");
        exit(-1);
    }
    cq->arr = tmp;
    cq->front = 0;
    cq->rear = 0;
    cq->len = len;
    return cq;
    
}

//判断循环队列是否为空，为空输出-1，非空输出1
int circularQueueIsEmpty(CQueue* cq) {
    return (cq->front == cq->rear) ? -1 : 1;
}

//判断循环队列是否已满，满了输出-1，没满输出1
int circularQueueIsFull(CQueue* cq) {
    return (((cq->rear+1)%(cq->len+1)) == cq->front) ? -1 : 1;
}

//向循环队列插入一个元素
void circularQueuePush(CQueue* cq, int data) {
    //先判断是否已经满了
    if (circularQueueIsFull(cq) == -1) {
        printf("已经满了，无法插入!\n");
        return ;
    }
    printf("入队\n");
    cq->arr[cq->rear++] = data;
    cq->rear = (cq->rear)%(cq->len+1);
}

//向循环队列删除一个元素
void circularQueuePop(CQueue* cq) {
    //先判断是否为空
    if (-1 == circularQueueIsEmpty(cq)) {
        printf("队列为空，无法删除!\n");
        return ;
    }
    printf("出队\n");
    cq->front++;
    cq->front = (cq->front)%(cq->len+1);
    
 }

//获取队头元素,为空返回-1
int circularQueueFront(CQueue* cq){
    if (-1 == circularQueueIsEmpty(cq)) {
        return -1;
    }
    return cq->arr[cq->front];
}

//获取队尾元素,为空返回-1
int circularQueueRear(CQueue* cq) {
    if (-1 == circularQueueIsEmpty(cq)) {
        return -1;
    }
    return cq->arr[(cq->rear+cq->len)%(cq->len+1)];
}

//释放空间
void circularQueueDestroy(CQueue* cq) {
    free(cq->arr);
    free(cq);
}

//打印队列
void circularPrint(CQueue* cq) {
    CQueue* cur = cq;
    int head = cur->front;
    int tail = cur->rear;
    int len = ((tail - head + cur->len)%cur->len == 0) ? cur->len : tail - head + cur->len%cur->len;
    while (len != 0) {
        --len;
        printf("%d ", cq->arr[head++]);
    }
    printf("\n");    
}
